﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.DependencyInjection;

namespace WucCloud.WebApi.Filter
{
    /// <summary>
    /// 权限功能校验
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
    public class AuthorizeCodeAttribute : Attribute, IAsyncAuthorizationFilter
    {
        /// <summary>
        /// 功能名称(权限名称)
        /// </summary>
        public string PermissionName { get; set; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="name"></param>
        public AuthorizeCodeAttribute(string name)
        {
            PermissionName = name;
        }

        /// <summary>
        /// 权限校验
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (!context.HttpContext.User.HasClaim(c => c.Value == PermissionName))
            {
                context.Result = new ForbidResult();
            }
            await Task.CompletedTask;
        }
    }
}
